package com.example.base.tools.upgrade

import okhttp3.Interceptor
import okhttp3.Response
import java.lang.Exception

/**  下载拦截器  **/
class DownloadInterceptor(
    private val downloadInfo: DownloadInfo,
    private val downloadListener: DownloadListener?
) : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        downloadListener?.onProgress(0)
        val request = chain.request()
        val originalResponse: Response
        try {
            originalResponse = chain.proceed(request)
        } catch (e: Exception) {
            e.printStackTrace()
            downloadListener?.onFailed(e)
            // return Response.Builder().build()
            return chain.proceed(request)
        }

        // if (originalResponse.isSuccessful.not()) originalResponse.close()

        // 替换掉原本的 ResponseBody 为我们自己定义的 DownloadResponseBody
        return originalResponse.newBuilder()
            .body(
                DownloadResponseBody(
                    originalResponse.body,
                    FileWriteTool.getFileStartPoint(
                        downloadInfo.apkSavePath,
                        downloadInfo.fileName
                    ),
                    progressListener = { progress ->
                        downloadListener?.onProgress(progress)
                    },
                    onErrorListener = {
                        downloadListener?.onFailed(Exception(it))
                    }
                ))
            .build()
    }

}